<?php

namespace App\Http\Controllers\Api\SmallApp\Order;

use App\Http\Controllers\Common\ApiController;
use App\Models\Common\China;
use App\Models\Repair\ReapirFactoryComment;
use App\Models\Repair\RepairFactory;
use App\Models\Repair\RepairFactoryAdmin;
use App\Models\User\User;
use Illuminate\Http\Request;

class RepairFactoryController extends ApiController {

    public function addComment(Request $request) {

        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        $user = User::where(compact('id'))->first();
        if(empty($user))
            return responseFail('未找到有效用户');
        $user_id = $id;
        $repair_factory_id = $request->input('repair_factory_id');
        $star = $request->input('star');
        $content = $request->input('content');
        $imgs = $request->input('img_urls');

        $this->validate($request, [
            'repair_factory_id'=>'required|Integer',
            'star'=>'required',
            'content'=>'required',
            //'img_urls'=>'required|array',
        ],[],[
            'star'=>'星级',
            'content'=>'评价内容',
            //'img_urls'=>'图片地址',
        ]);

        $info = compact('repair_factory_id','star','content','imgs','user_id');
        ReapirFactoryComment::create($info);
        return responseSuccess();
    }

    public function zan(Request $request) {
        $id = $request->input('id');
        ReapirFactoryComment::where(compact('id'))->increment('good');
        return responseSuccess();

    }

    public function detail(Request $request) {
        $id = $request->input('id');

        $records = RepairFactory::where(compact('id'))->with(['getComments'])->first();

        $userIds = array_column($records->getComments->toArray(), 'user_id');

        $users = User::whereIn('id',$userIds)->get(['wx_avatar','id','wx_nickname']);
        foreach ($records->getComments as $getComment) {
            $temp = $users->where('id',$getComment->user_id)->first();
            if(!empty($temp)){
                $getComment->wx_avatar =$temp->wx_avatar;
                $getComment->wx_nickname = $temp->wx_nickname;
            }else{
                $getComment->avatar ='';
                $getComment->nickname = '小宝';
            }

            //$getComment->nick_name = $users[$getComment->user_id]??'';
        }

        $phones = RepairFactoryAdmin::where('factory_id',$id)->pluck('phone')->implode(',');

        $records->phones = $phones;
        $records->star = $records->getStar();

        $mapArea = China::getMap();
        $prov =$mapArea[ $records->prov_code]??'';
        $city =$mapArea[ $records->city_code]??'';
        $county =$mapArea[ $records->county_code]??'';

        $records->address = $prov.$city.$county.$records->address;


        return responseSuccess($records->toArray());

    }

    public function index(Request $request) {

    }

}
